﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using System.IO;
using System.Runtime.Serialization.Formatters.Binary;
using System.Runtime.Serialization;

using BBCommon;

namespace Client
{
   public partial class ChatForm : Form
   {
      private string BBComBotName = "BBBot";
      private string PenduGameStartLetter = "_";
      PenduGame PenduGame;

      #region Methods

      private List<string> _listAllUser;
      private List<string> ListAllUser
      {
         get
         {
            if (this._listAllUser == null)
               this._listAllUser = new List<string>();

            return this._listAllUser;
         }
         set
         {
            this._listAllUser = value;
         }
      }

      /// <summary>
      /// Obtient la liste des utilisateurs sélectionnés
      /// </summary>
      /// <returns></returns>
      private List<string> GetSelectedUser()
      {
         List<string> ls = new List<string>();

         foreach (DataGridViewRow dgvr in this.dataGridView_users.SelectedRows)
         {
            ls.Add(dgvr.Cells[this.NameUser.Index].Value.ToString());
         }

         return ls;
      }

      /// <summary>
      /// Obtient la ligne correspondant à l'utilisateur
      /// </summary>
      /// <param name="nick"></param>
      /// <returns></returns>
      private DataGridViewRow GetRowByUserName(string nick)
      {
         foreach (DataGridViewRow dgvr in this.dataGridView_users.Rows)
         {
            if (dgvr.Cells[this.NameUser.Index].Value.ToString().Equals(nick))
               return dgvr;
         }

         return null;
      }

      private void Disconnect()
      {
         if (MessageBox.Show("Are you sure you want to disconnect ?", "Confirmation", MessageBoxButtons.YesNo) == DialogResult.Yes)
            Program.Client.Disconnect("Leaving");
      }

      private void CalculTimeElapsed()
      {
         int hour = DateTime.Now.Hour;
         if ((hour > 18) || (hour < 9))
         {
            this.toolStripProgressBar1.ProgressBar.Value = 0;
         }
         else
         {
            this.toolStripProgressBar1.ProgressBar.Value = (hour - 9) * 10;
         }
      }

      private void Knock()
      {         
         foreach (string str in this.GetSelectedUser())
            Program.Knock(str, this.GetSelectedConversation());
      }

      private void Coffee()
      {
         foreach (string str in this.GetSelectedUser())
            Program.Coffee(str, this.GetSelectedConversation());
      }

      private void Game()
      {
         foreach (string str in this.GetSelectedUser())
         {

         }
      }

      private void Eat()
      {
         foreach (string str in this.GetSelectedUser())
            Program.Eat(str, this.GetSelectedConversation());
      }

      /// <summary>
      /// Démarrer une conversation privée
      /// </summary>
      private void StartPrivateConversation()
      {
         List<string> str = new List<string>();
         str.Add(Player.Nick);
         foreach (string s in this.GetSelectedUser())
            if (!str.Contains(s))
               str.Add(s);

         BBConversation convers = Program.StartPrivateConversation(str);

         if (convers != null)
         {
            this.CreateTabPage(convers);
         }
      }

      private void AddPlayerIntoConversation(BBConversation conversation, string player)
      {
         if ((conversation != null) && (!conversation.Players.Contains(player)))
         {
            conversation.Players.Add(player);
            Program.JoinConversation(conversation, player);
         }
      }

      /// <summary>
      /// Obtient le tabpage concernant le message
      /// Créé le tabpage si celui ci n'existe pas
      /// </summary>
      /// <param name="message"></param>
      /// <returns></returns>
      private TabPage GetTabPage(BBMessage message)
      {
         if ((message != null) && (message.Conversation != null))
         {
            //Création du tab page
            if (!this.tabControl1.TabPages.ContainsKey(message.Conversation.ConversGUID.ToString()))
               this.CreateTabPage(message.Conversation);

            if (this.tabControl1.TabPages.ContainsKey(message.Conversation.ConversGUID.ToString()))
            {
               TabPage tp = this.tabControl1.TabPages[message.Conversation.ConversGUID.ToString()];
               tp.Tag = message.Conversation;
               //tp.Text = message.Conversation.ConversGUID.ToString();
               //tp.Text = message.Conversation.ToString();
               return tp;
            }
            else
               return null;
         }
         else
            return null;
      }

      /// <summary>
      /// Obtient le rich text box en fonction du tabpage
      /// </summary>
      /// <param name="tabPage"></param>
      /// <returns></returns>
      private RichTextBox GetRichTextBox(TabPage tabPage)
      {
         foreach (Control ctrl in tabPage.Controls)
         {
            if (ctrl is RichTextBox)
               return ctrl as RichTextBox;
         }

         return null;
      }

      /// <summary>
      /// On définit que le tab page a été modifié
      /// </summary>
      /// <param name="tabPage"></param>
      private void SetTabPageModified(TabPage tabPage, bool isModified)
      {
         if ((this.tabControl1.SelectedTab != tabPage) && (isModified))
         {
            //Modification d'un autre onglet
            tabPage.ImageIndex = 1;
         }
         else
         {
            //Autre
            tabPage.ImageIndex = 0;
         }

         //Recherche des utilisateurs connectés au serveur
         this.CreateDataGridViewConnectedUser();
      }

      /// <summary>
      /// Renommer une conversation
      /// </summary>
      private void RenameConversation()
      {
         if ((this.tabControl1.SelectedTab != null) && (this.tabControl1.SelectedTab.Tag != null))
         {
            RenameConversation rc = new RenameConversation(this.tabControl1.SelectedTab.Text);
            if (rc.ShowDialog() == DialogResult.OK)
            {
               this.tabControl1.SelectedTab.Text = rc.Value;
            }
         }
      }

      /// <summary>
      /// Ajoute une personne à la conversation
      /// </summary>
      private void AddPersonToConversation()
      {
         if ((this.tabControl1.SelectedTab != null) && (this.tabControl1.SelectedTab.Tag != null))
         {
            if (this.tabControl1.SelectedTab.Tag is BBConversation)
            {
               BBConversation conversation = this.tabControl1.SelectedTab.Tag as BBConversation;

               List<string> lst = new List<string>();

               foreach (string player in this.ListAllUser)
               {
                  if ((!conversation.Players.Contains(player)) && (!lst.Contains(player)))
                     lst.Add(player);
               }

               if (lst.Count > 0)
               {
                  AddANewPerson add = new AddANewPerson();
                  add.Players = lst;
                  if (add.ShowDialog() == DialogResult.OK)
                  {
                     foreach (string str in add.SelectedPlayers)
                        this.AddPlayerIntoConversation(conversation, str);
                  }
               }
               else
               {
                  MessageBox.Show("Nobody can be added to this conversation");
               }
            }
            else
            {
               MessageBox.Show("An error occured");
            }
         }
      }

      /// <summary>
      /// Fermeture d'un tab page
      /// </summary>
      private void CloseTabPage()
      {
         //if ((this.tabControl1.SelectedTab != null) && (this.tabControl1.SelectedTab.Tag != null))
         //{
         //    //Informe la communauté que la personne a quitté la page
         //    Program.LeaveConversation(this.tabControl1.SelectedTab.Tag as BBConversation, Player.Nick);

         //    this.tabControl1.TabPages.Remove(this.tabControl1.SelectedTab);
         //}

         this.CloseTabPage(this.tabControl1.SelectedTab);
      }

      private void CloseTabPage(TabPage tabPage)
      {
         if ((tabPage != null) && (tabPage.Tag != null))
         {
            //Informe la communauté que la personne a quitté la page
            Program.LeaveConversation(tabPage.Tag as BBConversation, Player.Nick);

            this.tabControl1.TabPages.Remove(tabPage);
         }
      }

      /// <summary>
      /// Création du data grid view
      /// </summary>
      private void CreateDataGridViewConnectedUser()
      {
         this.dataGridView_users.Rows.Clear();

         if (this.tabControl1.SelectedTab != null)
         {
            if ((this.tabControl1.SelectedTab.Tag != null) && (this.tabControl1.SelectedTab.Tag is BBConversation))
            {
               BBConversation conversation = this.tabControl1.SelectedTab.Tag as BBConversation;

               foreach (string nick in conversation.Players)
               {
                  DataGridViewRow dgvr = new DataGridViewRow();
                  //Création des cellules à partir du tableau que l'on souhaite
                  dgvr.CreateCells(this.dataGridView_users);
                  dgvr.Cells[this.LogoColumn.Index].Value = this.imageList_user.Images[0];
                  dgvr.Cells[this.NameUser.Index].Value = nick;
                  this.dataGridView_users.Rows.Add(dgvr);
               }
            }
            else
            {

               foreach (string nick in this.ListAllUser)
               {
                  DataGridViewRow dgvr = new DataGridViewRow();
                  //Création des cellules à partir du tableau que l'on souhaite
                  dgvr.CreateCells(this.dataGridView_users);
                  dgvr.Cells[this.LogoColumn.Index].Value = this.imageList_user.Images[0];
                  dgvr.Cells[this.NameUser.Index].Value = nick;
                  this.dataGridView_users.Rows.Add(dgvr);
               }
            }
         }
      }

      /// <summary>
      /// Création d'un tabpage
      /// </summary>
      /// <param name="message"></param>
      /// <returns></returns>
      private TabPage CreateTabPage(BBConversation conversation)
      {
         if (conversation != null)
         {
            this.tabControl1.TabPages.Add(conversation.ConversGUID.ToString(), conversation.ToString());

            if (this.tabControl1.TabPages.ContainsKey(conversation.ConversGUID.ToString()))
            {
               TabPage tabPage = this.tabControl1.TabPages[conversation.ConversGUID.ToString()];
               if (tabPage != null)
               {
                  RichTextBox richTextBox = new RichTextBox();
                  richTextBox.ReadOnly = true;
                  richTextBox.Dock = DockStyle.Fill;
                  richTextBox.BackColor = Color.White;
                  tabPage.BorderStyle = BorderStyle.FixedSingle;
                  tabPage.Controls.Add(richTextBox);

                  //Le tag de la tabpage correspond à la conversation
                  tabPage.Tag = conversation;

                  return tabPage;
               }
               else
                  return null;
            }
            else
               return null;
         }
         else
            return null;
      }

      private void SnowBall()
      {
         foreach (string str in this.GetSelectedUser())
         {
            TimeSpan span = DateTime.Now - lastBall;
            if (span.Hours < 1)
            {
               AppendSysMsg("You have no ball left. You get a new snowball every hour.");
               return;
            }

            Program.Shoot(str);
            lastBall += new TimeSpan(1, 0, 0);
         }

         ballTimer_Tick(null, null);
      }

      #endregion

      public PlayerCarac Player;

      // Font used
      public Font FontUsrMsg;
      public Font FontTimeStamp;
      public Font FontUsrNick;
      public Font FontAdmMsg;
      public Font FontSysMsg;

      private bool isAlreadyConnecting;
      private bool hasTriedFirstConnection;

      // Is Typing? event
      public sealed class TypingEvent : EventArgs
      {
         public bool isTyping;
         public TypingEvent(bool value)
         {
            isTyping = value;
         }
      }
      public event EventHandler<TypingEvent> TypingStateChanged;
      private bool isTyping;

      private ConnectForm CoForm;
      private ConnectingForm CuCoForm;
      private string lastTalkerNick;
      private DateTime lastTalkDate;

      public ChatForm()
      {
         ballSender = "";
         lastBall = DateTime.Now;
         lastBall -= new TimeSpan(3, 0, 0);
         ballTimer = new Timer();
         ballTimer.Interval = 60 * 1000;    // Every minute
         ballTimer.Tick += new EventHandler(ballTimer_Tick);

         InitializeComponent();

         this.timer1.Start();
         FontUsrMsg = new Font("Verdana", 8, FontStyle.Regular);
         FontTimeStamp = new Font("Verdana", 8, FontStyle.Regular);
         FontUsrNick = new Font("Verdana", 9, FontStyle.Bold);
         FontAdmMsg = new Font("Verdana", 8, FontStyle.Bold);
         FontSysMsg = new Font("Verdana", 8, FontStyle.Italic);

         lastTalkerNick = "";
         lastTalkDate = DateTime.MinValue;
         isTyping = false;

         //lbUserList.SmallImageList = new ImageList();
         //lbUserList.SmallImageList.Images.Add(Resource1.EmptyIcon);
         //lbUserList.SmallImageList.Images.Add(Resource1.Pen.ToBitmap());
         hasTriedFirstConnection = false;
         isAlreadyConnecting = false;

         // Registering on hide/show global event
         Program.HiddenStateChanged += new EventHandler(Program_HiddenStateChanged);
      }

      FormWindowState lastState;
      void Program_HiddenStateChanged(object sender, EventArgs e)
      {
         if (Program.IsAppHidden)
         {
            WindowState = FormWindowState.Minimized;
            Hide();
         }
         else
         {
            Show();
            if (WindowState == FormWindowState.Minimized)
               WindowState = FormWindowState.Normal;
         }
      }

      /// <summary>
      /// Obtient la conversation sélectionnée
      /// </summary>
      /// <returns></returns>
      private BBConversation GetSelectedConversation()
      {
         return this.tabControl1.SelectedTab.Tag as BBConversation;
      }

      private void btnSend_Click(object sender, EventArgs e)
      {
         if (!string.IsNullOrEmpty(this.tbInput.Text))
         {
            if (this.tabControl1.SelectedTab.Text == "All")
            {
               Program.Entered(this.tbInput.Text);
            }
            else
            {
               Program.PrivateMessage(this.tabControl1.SelectedTab.Tag as BBConversation, this.tbInput.Text, Player.Nick);
            }
            tbInput.Clear();
         }
      }

      private string GetTimeStamp()
      {
         int elapsed = DateTime.Now.Minute - lastTalkDate.Minute;
         if (elapsed > 0)
         {
            return "[" + DateTime.Now.ToShortTimeString() + "]\t";
         }
         else
         {
            return "\t";
         }
      }

      private void AppendTextLine(Font font, Color color, string text, bool decorated)
      {
         this.AppendTextLine(font, color, text, decorated, this.rtbChat);
      }

      private void AppendTextLine(Font font, Color color, string text, bool decorated, RichTextBox rtbChat)
      {
         // Save selection
         int lastSelStart, lastSelLength;
         lastSelStart = rtbChat.SelectionStart;
         lastSelLength = rtbChat.SelectionLength;

         // Set the cursor at the end
         rtbChat.Select(rtbChat.TextLength, 0);

         // Save font
         Font was = rtbChat.SelectionFont;
         Color wasColor = rtbChat.SelectionColor;

         // Append text line by line
         string[] lines = text.Split(Environment.NewLine[0]);
         foreach (string line in lines)
         {
            // Add timestamp
            rtbChat.SelectionFont = FontTimeStamp;
            rtbChat.SelectionColor = Color.Gray;
            rtbChat.AppendText(GetTimeStamp());
            rtbChat.Select(rtbChat.TextLength, 0);

            rtbChat.SelectionFont = font;
            if (decorated)
            {
               rtbChat.SelectionColor = Color.Black;
               rtbChat.AppendText("| ");
               rtbChat.Select(rtbChat.TextLength, 0);
            }
            string trimed_line = line;
            foreach (char c in Environment.NewLine)
               trimed_line = trimed_line.Trim(c);
            rtbChat.SelectionColor = color;
            rtbChat.AppendText(trimed_line + Environment.NewLine);
         }

         // Restore font
         rtbChat.SelectionColor = wasColor;
         rtbChat.SelectionFont = was;

         // Restore selection if needed
         if (lastSelLength > 0)
         {
            rtbChat.SelectionStart = lastSelStart;
            rtbChat.SelectionLength = lastSelLength;
         }

         lastTalkDate = DateTime.Now;
         Win32.ScrollRichTextBox(rtbChat);
      }

      private void tbInput_KeyDown(object sender, KeyEventArgs e)
      {
         // Auto send on return key
         if ((e.KeyCode == Keys.Return || e.KeyCode == Keys.Enter) && e.Modifiers != Keys.Control)
         {
            e.SuppressKeyPress = true;
            btnSend_Click(sender, null); // treat as enter click
         }
      }

      private void Form1_Shown(object sender, EventArgs e)
      {
         ballTimer_Tick(null, null);
         Program_HiddenStateChanged(null, null);
         Connect();
      }

      public void AppendChatMsg(string text, string nick, Color color)
      {
         TabPage tp = this.tabControl1.TabPages[0];

         if (tp != null)
         {
            //Définit l'onglet en modification
            this.SetTabPageModified(tp, true);

            RichTextBox rtb = this.GetRichTextBox(tp);
            if (rtb != null)
            {


               if (nick != "")
               {
                  TimeSpan elapsed = DateTime.Now - lastTalkDate;

                  // Display nick if necessary
                  if (lastTalkerNick != nick || elapsed.Minutes > 5)
                  {
                     AppendTextLine(FontUsrNick, Color.Black, nick + " says:", false);
                  }

                  // Display msg
                  AppendTextLine(FontUsrMsg, color, text, true);

                  lastTalkerNick = nick;
               }
               else
               {
                  // Display msg
                  AppendTextLine(FontAdmMsg, color, "Admin message: " + text, false);

                  lastTalkerNick = "";
               }
            }
         }
      }

      public void AppendChatMsgBBMessage(BBMessage msg, string text, string nick, Color color, string conversName)
      {
         //Récupération du tabpage utile pour afficher le message
         TabPage tp = this.GetTabPage(msg);

         if (tp != null)
         {
            //Définition de l'image pour dire que le tabpage est modifié
            this.SetTabPageModified(tp, true);

            RichTextBox rtb = this.GetRichTextBox(tp);

            if (rtb != null)
            {
               if (Player.Nick == this.BBComBotName)
               {
                  if (this.PenduGame != null)
                  {
                     //Vérification que les lettres sont bonnes
                     if (text.StartsWith(this.PenduGameStartLetter))
                     {
                        if (text.Length - this.PenduGameStartLetter.Length == 1)
                        {
                           this.PenduGame.AddLetter(text.Replace(this.PenduGameStartLetter, string.Empty));
                           this.DisplayPendu();
                           return;
                        }
                     }
                  }
               }

               if (nick != "")
               {
                  if ((rtb.Tag == null) || (!rtb.Tag.ToString().Equals(nick)))
                  {
                     AppendTextLine(FontUsrNick, Color.Black, nick + " says:", false, rtb);
                  }

                  AppendTextLine(FontUsrMsg, color, text, true, rtb);
                  
                  rtb.Tag = nick;
               }
               else
               {
                  AppendTextLine(FontAdmMsg, color, "Admin message: " + text, false, rtb);
               }
            }
         }
      }

      public void AppendSysMsg(string text)
      {
         AppendTextLine(FontSysMsg, Color.Black, text, false);
      }

      public void AppendSysMsgBBMessage(BBMessage message, string text, bool toReload)
      {
         TabPage tp = this.GetTabPage(message);

         if (tp != null)
         {
            RichTextBox rtb = this.GetRichTextBox(tp);

            if (rtb != null)
            {
               AppendTextLine(FontSysMsg, Color.Black, text, false, rtb);
               if (toReload)
                  this.CreateDataGridViewConnectedUser();
            }
         }
      }

      public void UserIsTypingMsg(string nick, bool isTyping, BBConversation convers)
      {
         if ((this.tabControl1.SelectedTab.Tag != null) && (this.tabControl1.SelectedTab.Tag is BBConversation))
         {
            if (convers.ConversGUID == ((BBConversation)this.tabControl1.SelectedTab.Tag).ConversGUID)
            {
               DataGridViewRow dgvr = this.GetRowByUserName(nick);
               if (dgvr != null)
               {
                  if (isTyping)
                  {
                     dgvr.Cells[this.LogoColumn.Index].Value = this.imageList_user.Images[1];
                  }
                  else
                  {
                     dgvr.Cells[this.LogoColumn.Index].Value = this.imageList_user.Images[0];
                  }

               }
            }
         }
      }

      public void UserIsTypingMsg(string nick, bool isTyping)
      {
         if (this.tabControl1.SelectedTab.Tag == null)
         {
            DataGridViewRow dgvr = this.GetRowByUserName(nick);
            if (dgvr != null)
            {
               if (isTyping)
               {
                  dgvr.Cells[this.LogoColumn.Index].Value = this.imageList_user.Images[1];
               }
               else
               {
                  dgvr.Cells[this.LogoColumn.Index].Value = this.imageList_user.Images[0];
               }

            }
         }
      }

      public void UserConnect(string nick, bool newUser)
      {
         if (!this.ListAllUser.Contains(nick))
            this.ListAllUser.Add(nick);


         //this.treeView1.Nodes.Add(nick, nick, 0);
         // Add the player to our player list
         //lbUserList.Items.Add(nick, nick, 0);
         if (newUser)
         {
            AppendSysMsg(nick + " has just connected");
         }

         this.CreateDataGridViewConnectedUser();
      }


      public void UserDisconnect(string nick, string reason)
      {
         if (this.ListAllUser.Contains(nick))         
            this.ListAllUser.Remove(nick);         

         AppendSysMsg(nick + " is disconnected. Reason is : \"" + reason + "\"");
         //this.treeView1.Nodes[nick].Remove();
         this.CreateDataGridViewConnectedUser();
      }

      public void Connect()
      {
         if (isAlreadyConnecting)
            return;

         isAlreadyConnecting = true;
         // Empty list box
         CuCoForm = new ConnectingForm();
         CoForm = new ConnectForm();

         //this.treeView1.Nodes.Clear();
         //lbUserList.Items.Clear();
         this.dataGridView_users.Rows.Clear();
         bool connected = false;
         bool firstrun = true;

         while (!connected)
         {
            if (!firstrun || (firstrun && !Program.AppConfig.AutoConnect) || hasTriedFirstConnection && WindowState != FormWindowState.Minimized)
            {
               if (CoForm.ShowDialog(this) != DialogResult.OK)
               {
                  // Clean exit
                  Application.Exit();
                  return;
               }
            }
            firstrun = false;

            // Create the player info
            Player = new PlayerCarac();
            Player.Nick = Program.AppConfig.Nick;
            Player.Type = (PlayerClass)CoForm.lbClass.SelectedIndex;            
            Player.TextColor = Program.AppConfig.TextColor;

            hasTriedFirstConnection = true;
            connected = (CuCoForm.ShowDialog(this) == DialogResult.OK);
         }

         // Change text color
         tbInput.ForeColor = Program.AppConfig.TextColor;

         isAlreadyConnecting = false;
         this.toolStripStatusLabel3.Text = Player.Nick;
      }

      private void ChatForm_SizeChanged(object sender, EventArgs e)
      {
         Program.IsAppHidden = (WindowState == FormWindowState.Minimized);
         Win32.ScrollRichTextBox(rtbChat);
      }

      private void tbInput_TextChanged(object sender, EventArgs e)
      {
         bool old = isTyping;

         if (tbInput.Text == "")
         {
            isTyping = false;
         }
         else
         {
            isTyping = true;
         }

         if (isTyping != old)
            TypingStateChanged(this.tabControl1.SelectedTab.Tag, new TypingEvent(isTyping));
      }

      private void ChatForm_Load(object sender, EventArgs e)
      {
         Program_HiddenStateChanged(null, null);
      }

      #region SnowBall Handling

      private string ballSender;
      DateTime lastBall;
      DateTime ballReceived;
      Timer ballTimer;
      private static System.Windows.Forms.NotifyIcon notifyIconNA;

      private void btnSnowball_Click(object sender, EventArgs e)
      {
         this.SnowBall();
      }

      internal void ShootSnowBall(string p)
      {
         if (ballSender != "")
         {
            Program.ShootResponse(ShootResponseDesc.Response.TOO_MUCH, p);
            return;
         }

         ballReceived = DateTime.Now;
         ballSender = p;

         // Initialize Notification Area Icon
         notifyIconNA = new System.Windows.Forms.NotifyIcon();
         notifyIconNA.Icon = Resource1.Snowflake;
         notifyIconNA.Text = p + " is throwing a snowball to you!";

         notifyIconNA.Visible = true;
         notifyIconNA.MouseClick += new MouseEventHandler(notifyIconNA_MouseClick);
      }

      void notifyIconNA_MouseClick(object sender, MouseEventArgs e)
      {
         TimeSpan span = DateTime.Now - ballReceived;

         notifyIconNA.Visible = false;
         notifyIconNA.Dispose();

         // User has 2 seconds
         if (span.Seconds <= 2)
         {
            // Ok !
            Program.ShootResponse(ShootResponseDesc.Response.AVOIDED, ballSender);
         }
         else
         {
            // Must counter it.
            SnowBallForm snowform = new SnowBallForm();
            if (snowform.ShowDialog(this) == DialogResult.Yes)
            {
               Program.ShootResponse(ShootResponseDesc.Response.COUNTERED, ballSender);
            }
            else
            {
               Program.ShootResponse(ShootResponseDesc.Response.TAKEN, ballSender);
            }
         }

         ballSender = "";
      }

      void ballTimer_Tick(object sender, EventArgs e)
      {
         // Update ball number
         TimeSpan span = DateTime.Now - lastBall;
         //Text = "BB Com(c) - Winter Edition : " + span.Hours + " snowball left";
      }

      #endregion

      private void btnKnock_Click(object sender, EventArgs e)
      {
         this.Knock();
      }



      private void toolStripButton1_Click(object sender, EventArgs e)
      {
         this.splitContainer1.Panel2Collapsed = !this.splitContainer1.Panel2Collapsed;
      }

      private void deconnexionToolStripMenuItem_Click(object sender, EventArgs e)
      {
         this.Disconnect();
      }

      private void quitterToolStripMenuItem_Click(object sender, EventArgs e)
      {
         this.Disconnect();
      }

      private void timer1_Tick(object sender, EventArgs e)
      {
         this.CalculTimeElapsed();
      }

      private void lbUserList_MouseClick(object sender, MouseEventArgs e)
      {
         //if (e.Button == MouseButtons.Right)
         //{
         //    if (this.lbUserList.SelectedItems.Count > 0)
         //    {
         //        if (this.lbUserList.SelectedItems.Count > 1)
         //            this.userNameToolStripMenuItem.Text = string.Concat(this.lbUserList.SelectedItems.Count.ToString(), " utilisateurs sélectionnées");
         //        else
         //            this.userNameToolStripMenuItem.Text = this.lbUserList.SelectedItems[0].Text;

         //        this.lbUserList.ContextMenuStrip = this.contextMenuStrip_userconnected;
         //    }
         //}
      }

      private void knockToolStripMenuItem_Click(object sender, EventArgs e)
      {
         this.Knock();
      }

      private void snowBallToolStripMenuItem_Click(object sender, EventArgs e)
      {
         this.SnowBall();
      }

      private void button1_Click(object sender, EventArgs e)
      {
         this.Coffee();
      }

      private void button2_Click(object sender, EventArgs e)
      {
         this.Eat();
      }

      private void coffeeToolStripMenuItem_Click(object sender, EventArgs e)
      {
         this.Coffee();
      }

      private void eatToolStripMenuItem_Click(object sender, EventArgs e)
      {
         this.Eat();
      }

      private void button3_Click(object sender, EventArgs e)
      {
      }

      private void demarrerUneConversationPriveToolStripMenuItem_Click(object sender, EventArgs e)
      {
         this.StartPrivateConversation();
      }

      private void tabControl1_SelectedIndexChanged(object sender, EventArgs e)
      {
         this.SetTabPageModified(this.tabControl1.SelectedTab, false);
      }

      private void fermerLaConversationToolStripMenuItem_Click(object sender, EventArgs e)
      {
         //Lorsque l'on souhaite fermer un onglet
         this.CloseTabPage();
      }

      private void tabControl1_MouseClick(object sender, MouseEventArgs e)
      {
         if (e.Button == MouseButtons.Right)
         {

         }
      }

      private void ajouterUneNouvellePersonneToolStripMenuItem_Click(object sender, EventArgs e)
      {
         this.AddPersonToConversation();
      }

      private void contextMenuStrip_tabcontainer_Opening(object sender, CancelEventArgs e)
      {
         this.renommerLaConversationToolStripMenuItem.Enabled = this.tabControl1.SelectedTab != null;
         this.ajouterUneNouvellePersonneToolStripMenuItem.Enabled = ((this.tabControl1.SelectedTab != null) && (this.tabControl1.SelectedTab.Tag != null));
         this.fermerLaConversationToolStripMenuItem.Enabled = ((this.tabControl1.SelectedTab != null) && (this.tabControl1.SelectedTab.Tag != null));
      }

      private void renommerLaConversationToolStripMenuItem_Click(object sender, EventArgs e)
      {
         this.RenameConversation();
      }

      private void ChatForm_FormClosing(object sender, FormClosingEventArgs e)
      {
         System.Windows.Forms.TabControl.TabPageCollection tabPages = this.tabControl1.TabPages;
         foreach (TabPage tabPage in tabPages)
         {
            this.CloseTabPage(tabPage);
         }
      }

      private void button3_Click_1(object sender, EventArgs e)
      {
         this.StartPendu();
      }

      #region Gestion du pendu

      private void StartPendu()
      {
         if (Player.Nick == this.BBComBotName)
         {
            PenduGame = new PenduGame();

            PenduGame.StartPenduGame();

            this.DisplayPendu();
         }
      }


      private void DisplayPendu()
      {
         if (this.PenduGame != null)
         {
            Program.PrivateMessage(this.tabControl1.SelectedTab.Tag as BBConversation, this.PenduGame.DisplayWord(), Player.Nick);
            Program.PrivateMessage(this.tabControl1.SelectedTab.Tag as BBConversation, this.PenduGame.DisplayResult(), Player.Nick);
         }
      }

      #endregion
   }
}
